<template>
  <el-dialog
    class="my-register-dialog"
    title="用户注册"
    :visible.sync="dialogFormVisible"
    center
    width="603px"
    @closed="closedHandler"
  >
    <!--closed注册关闭事  -->
    <el-form :model="form" :rules="rules" ref="regForm">
      <el-form-item label="头像" prop="avatar" :label-width="formLabelWidth">
        <el-upload
          class="avatar-uploader"
          :action="uploadURL"
          :show-file-list="false"
          name="image"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <!-- 如果imageUrl为空 不显示 反之显示  -->
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <!-- 正方形的小框框,图片为空才显示 -->
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username" :label-width="formLabelWidth">
        <el-input v-model="form.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
        <el-input v-model="form.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone" :label-width="formLabelWidth">
        <el-input v-model="form.phone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
        <el-input v-model="form.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.code" autocomplete="off"></el-input>
          </el-col>
          <el-col :offset="1" :span="7"
            ><img class="code-img" @click="changeImgUrl" :src="codeURL" alt=""
          /></el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.rcode" autocomplete="off"></el-input>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-button :disabled="delayTime !== 0" @click="getCode">{{
              btnText
            }}</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 导入 方法
import { getSMSCode, register } from '@/api/register'

export default {
  name: 'register',
  data () {
    return {
      // 是否显示
      dialogFormVisible: false,
      // 表单数据
      form: {
        // 用户名
        username: '',
        // 手机号
        phone: '',
        // 邮箱
        email: '',
        // 头像地址
        avatar: '',
        // 密码
        password: '',
        // 短信验证码
        rcode: '',
        // 图形验证码
        code: ''
      },
      // 校验规则
      rules: {
        username: [
          {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 11,
            message: '用户名长度为 2 到 11',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号格式有误',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '邮箱格式有误',
            trigger: 'blur'
          }
        ],
        avatar: [
          {
            required: true,
            message: '头像不能为空',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 18,
            message: '密码的长度为 6 到 18',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '图形验证码不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 4,
            message: '图形验证码的长度为 4',
            trigger: 'blur'
          }
        ],
        rcode: [
          {
            required: true,
            message: '短信验证码不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 4,
            message: '短信验证码的长度为 4',
            trigger: 'blur'
          }
        ]
      },
      // 左侧宽度
      // formLabelWidth: '87px'
      // 87-25=62
      formLabelWidth: '72px',
      // 本地图片预览地址
      imageUrl: '',
      // 图片上传地址
      uploadURL: process.env.VUE_APP_BaseURL + '/uploads',
      // 验证码地址
      codeURL: process.env.VUE_APP_BaseURL + '/captcha?type=sendsms',
      // 验证码按钮的文本
      btnText: '获取用户验证码',
      // 倒计时
      delayTime: 0
    }
  },
  methods: {
    // closedHandler 关闭对话框回调函数
    closedHandler () {
      this.$refs.regForm.resetFields()
    },
    // 提交表单 注册
    submitForm () {
      this.$refs.regForm.validate(valid => {
        if (valid) {
          // alert('submit!')
          // this.$message.success('校验成功')
          // 获取参数 es6的解构
          const { username, phone, email, avatar, password, rcode } = this.form
          register({
            username,
            phone,
            email,
            avatar,
            password,
            rcode
          }).then(res => {
            console.log(res)
            if (res.data.code === 200) {
              this.$message.success('注册成功')
              this.dialogFormVisible = false
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          // console.log('error submit')
          this.$message.error('数据格式有误,请检查重新上输入')
          return false
        }
      })
    },
    // 获取短信验证码(通过接口获取)
    getCode () {
      // 记录正确的次数
      let num = 0
      this.$refs.regForm.validateField(['phone', 'code'], errMsg => {
        if (errMsg === '') {
          num++
        }
      })
      // 两次有任一一次未成功
      if (num !== 2) {
        return
      }
      if (this.delayTime === 0) {
        // 设置时间
        this.delayTime = 5
        // 修改按钮文本
        this.btnText = `等待${this.delayTime}S`
        // 开启倒计时
        const interId = setInterval(() => {
          this.delayTime--
          // 倒计时结束
          if (this.delayTime === 0) {
            // 清除定时器
            clearInterval(interId)
            // 文本还原
            this.btnText = '获取用户验证码'
            // 不执行后续逻辑
            return
          }
          // 修改按钮文本
          this.btnText = `等待${this.delayTime}S`
        }, 1000)
      }
      // 获取手机号和验证码
      const { phone, code } = this.form
      // 调用方法
      getSMSCode({
        phone,
        code
      }).then(res => {
        console.log('res:', res)
        if (res.data.code === 200) {
          this.$message.success('验证码:' + res.data.data.captcha)
        }
      })
    },
    // 修改图片地址
    changeImgUrl () {
      // this.codeURL =
      //   process.env.VUE_APP_BaseURL + '/captcha?type=sendsms&t=' + Date.now()
      this.codeURL =
        process.env.VUE_APP_BaseURL + '/captcha?type=sendsms&t=' + Math.random()
    },
    // 上传成功回调函数
    handleAvatarSuccess (res, file) {
      // console.log('res:', res)
      // 保存头像地址 之后注册要用
      this.form.avatar = res.data.file_path
      // 上传成功之后本地预览图片
      this.imageUrl = URL.createObjectURL(file.raw)
      // 上传成功清空错误提示
      this.$refs.regForm.clearValidate('avatar')
    },
    beforeAvatarUpload (file) {
      const isJPG =
        ['image/jpeg', 'image/png', 'image/gif'].indexOf('image/jpeg') !== -1
      // 必须小于2m
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less">
.my-register-dialog {
  .el-dialog__header {
    // background-color: skyblue;
    // to right 设置方向
    background: linear-gradient(to right, #01c6fa 28%, #1493fa 96%);
  }
  .el-dialog__title {
    color: white;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader {
    text-align: center;
  }
  .code-img {
    display: block;
    width: 100%;
    cursor: pointer;
  }
  .el-dialog--center .el-dialog__body {
    padding-left: 15px;
  }
}
</style>
